﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices.Automation;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using OrbitOne.CRMLyncInfoDashboard.CRM.OData;

namespace OrbitOne.CRMLyncInfoDashboard.CRM
{
    [Export(typeof(IWindowUtility))]
    public class WindowUtility : IWindowUtility
    {
        private readonly IClientScript m_clientScript;

        [ImportingConstructor]
        public WindowUtility(IClientScript clientScript)
        {
            m_clientScript = clientScript;
        }

       

        public EntityModelTypes PreviewEntityType { get; set; }

        public string NewEntityUrlPattern
        {
            get
            {
                return CombineUri(m_clientScript.GetServerUrl().ToString(),
                                  Application.Current.Resources["NewEntityUrlPattern"].ToString());
            }
        }

        public string NewNoteUrlPattern
        {
            get
            {
                return CombineUri(m_clientScript.GetServerUrl().ToString(),
                                  Application.Current.Resources["NewNoteUrlPattern"].ToString());

            }
        }
        public string EditEntityUrlPattern
        {
            get
            {
                return CombineUri(m_clientScript.GetServerUrl().ToString(),
                                  Application.Current.Resources["EditEntityUrlPattern"].ToString());
            }
        }

        public string NewAccountUrl { get { return string.Format(NewEntityUrlPattern, "account"); } }
        public string NewContactUrl { get { return string.Format(NewEntityUrlPattern, "contact"); } }
        public string NewLeadUrl { get { return string.Format(NewEntityUrlPattern, "lead"); } }
        public string NewPhoneCallUrl { get { return string.Format(NewEntityUrlPattern, "phonecall"); } }
        public string NewTaskUrl { get { return string.Format(NewEntityUrlPattern, "task"); } }
       
        public string CombineUri(string baseUri, string relativeUri)
        {
            return string.Format("{0}/{1}", baseUri.TrimEnd('/'), relativeUri.TrimStart('/'));
        }


        public string EditEntityUrl(string entityType, Guid id)
        {
            return string.Format(EditEntityUrlPattern, entityType, id);
        }

        public string EditAccountUrl(Guid id)
        {
            return EditEntityUrl("account", id);
        }
        public string EditContactUrl(Guid id)
        {
            return EditEntityUrl("contact", id);
        }
        public string EditLeadUrl(Guid id)
        {
            return EditEntityUrl("lead", id);
        }

        public static void OpenPage(string targetUrl)
        {
            HtmlPage.Window.Invoke("OpenUrl", targetUrl);
        }

        public void EditEntityWindow<T>(T entityModel) where T : IEntityModel
        {
            var url = "";

            var entityModelType = (EntityModelTypes)Enum.Parse(typeof(EntityModelTypes), entityModel.GetType().Name, true);
            switch (entityModelType)
            {
                case EntityModelTypes.AccountModel:
                    url = EditAccountUrl(entityModel.Id);
                    break;
                case EntityModelTypes.ContactModel:
                    url = EditContactUrl(entityModel.Id);
                    break;
                case EntityModelTypes.LeadModel:
                    url = EditLeadUrl(entityModel.Id);
                    break;
            }
            OpenPage(url);
        }


        public void CreateNewEntityWindow<T>(T entityModel, Expression<Func<T, object>>[] autoCompletedProperties)
        {
            var url = "";
            var properties = autoCompletedProperties.Select(autoCompletedProperty =>
                new
                {
                    PropertyName = GetPropertyName(autoCompletedProperty).ToLower(),
                    PropertyValue = GetProperty(autoCompletedProperty, entityModel)
                }
                );

            var propertiesInQueryString = properties
                .Select(property => string.Format("{0}={1}", property.PropertyName, property.PropertyValue));

            var queryStringComponents = propertiesInQueryString;

            var extraQueryString = HttpUtility.UrlEncode(string.Join("&", queryStringComponents));

            var entityModelType = (EntityModelTypes)Enum.Parse(typeof(EntityModelTypes), entityModel.GetType().Name, true);
            switch (entityModelType)
            {
                case EntityModelTypes.AccountModel:
                    url = GetNewEntityUrl(NewAccountUrl, extraQueryString);
                    break;
                case EntityModelTypes.ContactModel:
                    url = GetNewEntityUrl(NewContactUrl, extraQueryString);
                    break;
                case EntityModelTypes.LeadModel:
                    url = GetNewEntityUrl(NewLeadUrl, extraQueryString);
                    break;
                case EntityModelTypes.PhoneCallModel:
                    url = GetNewEntityUrl(NewPhoneCallUrl, extraQueryString);
                    break;
                case EntityModelTypes.NoteModel:
                    url = string.Format(NewEntityUrlPattern, (int)PreviewEntityType);
                    break;
                case EntityModelTypes.TaskModel:
                    url = GetNewEntityUrl(NewTaskUrl, extraQueryString);
                    break;
            }
            //MessageBox.Show(url);
            OpenPage(url);
        }

        public void CreateNewEntityWindow<T>(T entityModel, Expression<Func<T, object>>[] autoCompletedProperties, IDictionary<string, string> autoCompleteFormFields)
        {
            var url = "";
            var properties = autoCompletedProperties.Select(autoCompletedProperty =>
                new
                    {
                        PropertyName = GetPropertyName(autoCompletedProperty).ToLower(),
                        PropertyValue = GetProperty(autoCompletedProperty, entityModel)
                    }
                );
            
            var propertiesInQueryString = properties
                .Select(property => string.Format("{0}={1}", property.PropertyName, property.PropertyValue));

            var formFieldsInQueryString = autoCompleteFormFields
                .Select(formField => string.Format("{0}={1}", formField.Key, formField.Value));

            var queryStringComponents = propertiesInQueryString.Concat(formFieldsInQueryString);

            var extraQueryString = HttpUtility.UrlEncode(string.Join("&", queryStringComponents));

            var entityModelType = (EntityModelTypes)Enum.Parse(typeof(EntityModelTypes), entityModel.GetType().Name, true);
            switch (entityModelType)
            {
                case EntityModelTypes.AccountModel:
                    url = GetNewEntityUrl(NewAccountUrl, extraQueryString);
                    break;
                case EntityModelTypes.ContactModel:
                    url = GetNewEntityUrl(NewContactUrl, extraQueryString);
                    break;
                case EntityModelTypes.LeadModel:
                    url = GetNewEntityUrl(NewLeadUrl, extraQueryString);
                    break;
                case EntityModelTypes.PhoneCallModel:
                    url = GetNewEntityUrl(NewPhoneCallUrl, extraQueryString);
                    break;
                case EntityModelTypes.NoteModel:
                    url = string.Format(NewNoteUrlPattern, autoCompleteFormFields["pId"], autoCompleteFormFields["pType"]);
                    break;
                case EntityModelTypes.TaskModel:
                    url = GetNewEntityUrl(NewTaskUrl, extraQueryString);
                    break;
            }
            //MessageBox.Show(url);
            OpenPage(url);
        }

        public string GetNewEntityUrl(string newEntityUrlPattern, string queryString)
        {
            return string.Format("{0}&extraqs={1}", newEntityUrlPattern, queryString);
        }

        public void CreateNewEntityWindowWithoutAutocompletedFields<T>(T entityModel)
        {
            var url = "";

            var entityModelType = (EntityModelTypes)Enum.Parse(typeof(EntityModelTypes), entityModel.GetType().Name, true);
            switch (entityModelType)
            {
                case EntityModelTypes.AccountModel:
                    url = NewAccountUrl;
                    break;
                case EntityModelTypes.ContactModel:
                    url = NewContactUrl;
                    break;
                case EntityModelTypes.LeadModel:
                    url = NewLeadUrl;
                    break;
                case EntityModelTypes.PhoneCallModel:
                    url = NewPhoneCallUrl;
                    break;
                case EntityModelTypes.NoteModel:
                    url = string.Format(NewNoteUrlPattern, (int)PreviewEntityType);
                    break;
                case EntityModelTypes.TaskModel:
                    url = NewTaskUrl;
                    break;
            }
            OpenPage(url);
        }

        public object GetProperty<TIn, TOut>(Expression<Func<TIn, TOut>> expression, object obj)
        {
            try
            {
                return ((PropertyInfo)(GetMemberExpression(expression).Member)).GetValue(obj, null);
            }
            catch (Exception ex)
            {
                throw new Exception(expression.ToString(), ex);
            }
        }

        public string GetPropertyName<TIn, TOut>(Expression<Func<TIn, TOut>> expression)
        {
            try
            {
                return GetMemberExpression(expression).Member.Name;
            }
            catch (Exception ex)
            {
                throw new Exception(expression.ToString(), ex);
            }
        }

        private static MemberExpression GetMemberExpression<TIn, TOut>(Expression<Func<TIn, TOut>> expression)
        {
            switch (expression.Body.NodeType)
            {
                case ExpressionType.MemberAccess:
                    return ((MemberExpression)(expression.Body));

                case ExpressionType.Call:
                    return ((MemberExpression)(((MethodCallExpression)(expression.Body)).Object));

                default:
                    return ((MemberExpression)(((UnaryExpression)(expression.Body)).Operand));
            }
        }
    }
}
